
#include <vector>
#include <iostream>
using std::cout;
using std::endl;
using std::vector;

void test0()
{
    //vector<int> numbers;
    vector<int> numbers(10);
    //int arr[5] = {1, 2, 3, 4, 5};
    //vector<int> numbers(arr, arr + 5);
    //vector<int> numbers = {1, 2, 3, 4, 5};
    //vector<int> numbers{1, 2, 3, 4, 5};
    cout << "numbers'size:" << numbers.size() << endl;
    cout << "numbers'capacity:" << numbers.capacity() << endl;
    for(auto & num : numbers)
    {
        cout << num << " ";
    }
    cout << endl;
}

void display(const vector<int>  & c)
{
    cout << "c's size:" << c.size() << endl
         << "c's capacity:" << c.capacity() << endl;
}

void test1()
{
    //动态扩容的步骤:
    //当size == capacity时，假设还要再添加新元素
    //1. 先申请 2 * capacity的新空间
    //2. 再将原来空间中的元素复制到新空间
    //3. 释放原来的空间
    //4. 在新空间中添加新元素
    vector<int> numbers;
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    
    //vector的底层实现:
    cout << "sizeof(numbers):" << sizeof(numbers) << endl;
}

void test2()
{
    //在使用的过程中，应该尽量减少动态扩容的次数
    //int arr[100] = {0};
    vector<int> numbers;
    numbers.reserve(1000);//只申请空间，并不添加元素
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);
    numbers.push_back(1);
    display(numbers);

    //减少到刚刚好
    numbers.shrink_to_fit();
    display(numbers);
    //希望在保证现有不变的情况下，进行扩容
    numbers.resize(30);
    display(numbers);
    for(auto & num : numbers) {
        cout << num << " ";
    }
    cout << endl;
}


int main()
{
    /* test0(); */
    /* test1(); */
    test2();
    return 0;
}

